package com.ruoyi.crm.service.impl;

import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.crm.domain.*;
import com.ruoyi.crm.domain.vo.ContractVo;
import com.ruoyi.crm.mapper.ActivityMapper;
import com.ruoyi.crm.mapper.ContractMapper;
import com.ruoyi.crm.mapper.CourseMapper;
import com.ruoyi.crm.modules.mq.CrmMqProducer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.mapper.BusinessMapper;
import com.ruoyi.crm.service.IBusinessService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 商机Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-01
 */
@Service
public class BusinessServiceImpl implements IBusinessService
{
    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private AssignRecordServiceImpl assignRecordService;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private ActivityMapper activityMapper;

    /**
     * 查询商机
     *
     * @param id 商机主键
     * @return 商机
     */
    @Override
    public Business selectBusinessById(Long id)
    {
        return businessMapper.selectBusinessById(id);
    }

    /**
     * 查询商机列表
     *
     * @param business 商机
     * @return 商机
     */
    @Override
    public List<Business> selectBusinessList(Business business)
    {
        return businessMapper.selectBusinessList(business);
    }

    /**
     * 新增商机
     *
     * @param business 商机
     * @return 结果
     */
    @Override
    public int insertBusiness(Business business)
    {
        business.setCreateBy(SecurityUtils.getUsername());
        business.setCreateTime(DateUtils.getNowDate());
        return businessMapper.insertBusiness(business);
    }

    /**
     * 修改商机
     *
     * @param business 商机
     * @return 结果
     */
    @Override
    public int updateBusiness(Business business)
    {
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(new Date());
        return businessMapper.updateBusiness(business);
    }

    /**
     * 批量删除商机
     *
     * @param ids 需要删除的商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessByIds(Long[] ids)
    {
        return businessMapper.deleteBusinessByIds(ids);
    }

    /**
     * 删除商机信息
     *
     * @param id 商机主键
     * @return 结果
     */
    @Override
    public int deleteBusinessById(Long id)
    {
        return businessMapper.deleteBusinessById(id);
    }

    /**
     * 1.修改分配记录latest为0
     * 2.修改商机状态为踢回公海
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int giveBack(Long id) {
//        AssignRecord assignRecord=new AssignRecord();
//        assignRecord.setId(id);
//        assignRecord.setType(AssignRecord.Type.BUSINESS.getValue());
//        assignRecord.setLatest(AssignRecord.LatesStatus.STALE.getValue());
//        assignRecordService.updateAssignRecord(assignRecord);
        Business business=businessMapper.selectBusinessById(id);
        business.setStatus(Clue.Status.FALSE.getValue());
        return businessMapper.updateBusiness(business);
    }

    @Override
    public int reset(Long id) {
        // 分配商机给当前用户，即谁捞取的商机就属于谁
        AssignRecord assignRecord=new AssignRecord();
        assignRecord.setType(AssignRecord.Type.BUSINESS.name());
        assignRecord.setAssignId(id);
        assignRecord.setUserId(SecurityUtils.getUserId());
        assignRecord.setDeptId(SecurityUtils.getDeptId());
        assignRecord.setCreateTime(new Date());
        assignRecord.setUserName(SecurityUtils.getUsername());
        return assignRecordService.insertAssignRecord(assignRecord);
    }

    @Resource
    private CrmMqProducer crmMqProducer;
    @Transactional
    @Override
    public int transformCustomer(ContractVo contractVo) {
        // 更新商机状态
        Business business=businessMapper.selectBusinessById(contractVo.getId());
        if (business.getCourseId()==null){
            throw new RuntimeException("商机里面没有选择课程，无法转换客户合同");
        }
        if (contractMapper.selectContractByNo(contractVo.getContractNo())!=null){
            throw new RuntimeException("合同编号已经存在，无法转换客户合同");
        }
        business.setStatus(Clue.Status.TO_CUSTOMER.getValue());
        business.setUpdateBy(SecurityUtils.getUsername());
        business.setUpdateTime(new Date());
        businessMapper.updateBusiness(business);
        // 插入合同
        Contract contract=new Contract();
        BeanUtils.copyProperties(business,contract);
        contract.setBusinessId(contractVo.getId());
        contract.setContractNo(contractVo.getContractNo());
        contract.setFileName(contractVo.getFileName());
        contract.setPhone(contractVo.getPhone());
        contract.setEmail(contractVo.getEmail());
        String businessKey= Seq.getId();
        contract.setId(businessKey);
        contract.setCreateBy(SecurityUtils.getUsername());
        contract.setCreateTime(DateUtils.getNowDate());
        contract.setDeptId(SecurityUtils.getDeptId());
        contract.setStatus("4");
        // 根据活动计算优惠后的金额
        setContractOrder(contract);
        contractMapper.insertContract(contract);
//        通过邮件和短信发送序列号给用户
        crmMqProducer.produceContractCreatedMessage(contract);// 邮件
        return 1;
    }

    private void setContractOrder(Contract contract){
        // 商机里面选课程
        Course course=courseMapper.selectCourseById(contract.getCourseId()); // 找出课程
        Activity activity=null;
        if (contract.getActivityId()!=null){
            activity=activityMapper.selectActivityById(contract.getActivityId()); // 找出商机里面参加的活动，如果活动不等于空，查询出来
        }
        if (activity==null){
            contract.setContractOrder(course.getPrice()); // 没参加活动，就是标准价钱
        }else {
            if ("1".equals(activity.getType())){
                contract.setDiscountType("课程折扣");
                contract.setContractOrder(activity.getDiscount()/10.0*course.getPrice());
            }else {
                contract.setDiscountType("代金劵");
                contract.setContractOrder(course.getPrice()-activity.getVouchers());
            }

        }
    }
}
